package org.example.maven.service.Impl;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.example.maven.mapper.collectionMapper;
import org.example.maven.mapper.provenanceSourceMapper;
import org.example.maven.pojo.ProvenanceSource;

import org.example.maven.service.ProvenanceSourceService;

import org.example.maven.utils.ExcelUtils;
import org.example.maven.utils.excel.ExcelDateUtils;
import org.example.maven.utils.excel.ExcelRowParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class provenanceSourceServiceImpl implements ProvenanceSourceService, ExcelRowParser<ProvenanceSource> {
    @Autowired
    private provenanceSourceMapper provenanceSourceMapper;
    @Autowired
    private collectionMapper collectionMapper;
    //获取最新的藏品id（excel）
    private Integer latestCollectionId;
    @Override
    public void addProvenanceSource(ProvenanceSource provenanceSource) {
        provenanceSourceMapper.addProvenanceSource(provenanceSource);
    }

    @Override
    public ProvenanceSource getProvenanceSourceById(Integer id) {
        return provenanceSourceMapper.getProvenanceSourceById(id);
    }

    @Override
    public ProvenanceSource parse(Row row, int rowNum) throws Exception {
        ProvenanceSource relic=new ProvenanceSource();
        String Value=ExcelUtils.getCellStringValue(row.getCell(11));
        ProvenanceSource.ProvenanceSourceAcquisitionType type= ProvenanceSource.ProvenanceSourceAcquisitionType.fromChineseName(Value);
        relic.setAcquisitionType(type);//获取来源形式
        // 修改为（安全处理）
        Cell dateCell = row.getCell(12);
        try {
            if (dateCell != null && DateUtil.isCellDateFormatted(dateCell)) {
                LocalDate acquisitionDate = ExcelDateUtils.getCellLocalDateValue(dateCell);
                relic.setAcquisitionDate(acquisitionDate);
            } else {
                System.out.println("第 " + rowNum + " 行捐赠日期为空或格式错误，已设为默认值");
                relic.setAcquisitionDate(LocalDate.now()); // 空值时设为当天日期
            }
        } catch (Exception e) {
            System.out.println("第 " + rowNum + " 行日期解析异常，已重置为当前日期");
            relic.setAcquisitionDate(LocalDate.now());
        }
        relic.setDonorName(ExcelUtils.getCellStringValue(row.getCell(13)));//获取捐赠人信息
        relic.setSourceDetail(ExcelUtils.getCellStringValue(row.getCell(14)));//获取捐赠详情
        relic.setCertificateNo(ExcelUtils.getCellStringValue(row.getCell(15)));//获取捐赠赠书id
        relic.setCollectionId(collectionMapper.getIdByCollectionInternalId(ExcelUtils.getCellStringValue(row.getCell(0))));

        System.out.println(relic);
        return relic;
    }
}
